package com.dimples.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dimples.common.entity.SecurityUser;
import com.dimples.common.enums.LoggingTypeEnum;
import com.dimples.common.enums.OpsLogTypeEnum;
import com.dimples.common.enums.StatusEnum;
import com.dimples.common.page.metadata.OrderItem;
import com.dimples.common.page.metadata.Page;
import com.dimples.common.transport.QueryRequest;
import com.dimples.common.util.AddressUtil;
import com.dimples.common.util.HttpContextUtil;
import com.dimples.common.util.SpringContextHolder;
import com.dimples.system.entity.Logging;
import com.dimples.system.mapper.LoggingMapper;
import com.dimples.system.service.LoggingService;

import org.lionsoul.ip2region.DbSearcher;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.TimerTask;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2021/8/12
 */
@Service
public class LoggingServiceImpl extends ServiceImpl<LoggingMapper, Logging> implements LoggingService {

    @Override
    public TimerTask saveOperaLog(Logging log) {
        return new TimerTask() {
            @Override
            public void run() {
                // 远程查询操作地点
                log.setOperateAddr(AddressUtil.getAddress(log.getOperateIp(), DbSearcher.BTREE_ALGORITHM));
                SpringContextHolder.getBean(LoggingService.class).save(log);
            }
        };
    }

    @Override
    public Logging savaLoginLog(SecurityUser securityUser) {
        Logging logging = new Logging();
        HttpServletRequest request = HttpContextUtil.getRequest();
        logging.setTitle("用户登陆");
        logging.setBusinessType(OpsLogTypeEnum.LOGIN.name());
        logging.setMethod(request.getMethod());
        logging.setOperateName(securityUser.getUsername());
        logging.setOperateUrl(request.getRequestURI());
        logging.setOperateIp(securityUser.getLoginDetails().getIpAddr());
        logging.setOperateAddr(AddressUtil.getAddress(logging.getOperateIp(), DbSearcher.BTREE_ALGORITHM));
        logging.setSuccess(StatusEnum.YES.getCode());
        logging.setBrowser(HttpContextUtil.getBrowserName(request) + " " + HttpContextUtil.getBrowserVersion(request));
        logging.setCreateTime(new Date());
        logging.setSystemOs(HttpContextUtil.getOsName(request));
        logging.setLoggingType(LoggingTypeEnum.LOGIN.name());
        this.save(logging);
        return logging;
    }

    @Override
    public Page<Logging> findLog(Logging logging, QueryRequest queryRequest) {
        Page<Logging> page = new Page<>(queryRequest.getPageNumber(), queryRequest.getPageSize());
        page.setOrders(OrderItem.descs("CREATE_TIME"));
        page.setRecords(this.baseMapper.listLog(page, logging));
        return page;
    }
}
